<?php
/*********************************************
  CPG Dragonfly™ CMS
  ********************************************
  Copyright © 2004 - 2007 by CPG-Nuke Dev Team
  http://dragonflycms.org

  Dragonfly is released under the terms and conditions
  of the GNU GPL version 2 or any later version
**********************************************/
if (!defined('ADMIN_PAGES')) { exit; }
if (!can_admin('smilies')) { die('Access Denied'); }
Dragonfly_Page::setTitle('. '._BC_DELIM.' Smiles Utility');

$smilies_path = 'images/smiles/';
$delimeter = '=+:';

function smile_edit($smile_data)
{
	Dragonfly_Output_Js::add('themes/admin/javascript/admin_smilies.js');
	global $smilies_path;

	$smiley_images = array();
	// Read a listing of uploaded smilies for use in the add or edit smiley code...
	$dir = opendir($smilies_path);
	while ($file = readdir($dir)) {
		if (!is_dir($smilies_path . $file)) {
			$img_size = getimagesize($smilies_path . $file);
			if ($img_size[0] && $img_size[1]) {
				$smiley_images[] = $file;
			}
		}
	}
	closedir($dir);
	if (!$smile_data['smile_url']) { $smile_data['smile_url'] = $smiley_images[0]; }

	$TPL = Dragonfly::getKernel()->OUT;
	$TPL->smiley = $smile_data;
	$TPL->smilies_path = $smilies_path;
	$TPL->smiley_images = $smiley_images;
	$TPL->display('admin/smilies/edit');
}

// Select main mode
if (isset($_GET['import_pack']))
{
	if (!empty($_POST['smile_pak'])) {
		if (!Security::check_post()) { cpg_error(_SEC_ERROR); }
		// The user has already selected a smile_pak file.. Import it.
		$smiles = array();
		if (!empty($_POST['clear_current'])) {
			$db->query("DELETE FROM {$db->TBL->bbsmilies}");
		}
		else {
			$cur_smilies = $db->uFetchAll("SELECT code FROM {$db->TBL->bbsmilies}");
			for ($i = 0; $i < count($cur_smilies); $i++) {
				$smiles[$cur_smilies[$i]['code']] = 1;
			}
		}

		$fcontents = file($smilies_path . $_POST['smile_pak']);

		if (empty($fcontents)) {
			cpg_error('The smiley pak file could not be read');
		}

		$tbl = $db->TBL->bbsmilies;
		for ($i = 0; $i < count($fcontents); $i++) {
			$smile_data = explode($delimeter, trim(Fix_Quotes($fcontents[$i])));
			for ( $j = 2; $j < count($smile_data); $j++) {
				// Replace > and < with the proper html_entities for matching.
				$smile_code = str_replace('>', '&gt;', str_replace('<', '&lt;', $smile_data[$j]));
				$smiley = array(
					'smile_url' => $smile_data[0],
					'emoticon'  => $smile_data[1]
				);
				if ($smiles[$smile_code] == 1) {
					if (!empty($_POST['replace_existing'])) {
						$tbl->update($smiley, array('code'=>$smile_code));
					}
				}
				else {
					$smiley['code'] = $smile_code;
					$tbl->insert($smiley);
				}
			}
		}
		Dragonfly::getKernel()->CACHE->delete('bbsmilies');
		cpg_error('The smiley pack was successfully installed', 'Smiles Utility', URL::admin('smilies'));
	}
	else {
		// Display the script to get the smile_pak cfg file...
		$smiley_paks = array();
		$dir = opendir($smilies_path);
		while ($file = readdir($dir)) {
			if (!is_dir($smilies_path . $file) && preg_match('#\.pak$#', $file)) {
				$smiley_paks[] = $file;
			}
		}
		closedir($dir);
		$TPL = Dragonfly::getKernel()->OUT;
		$TPL->smiley_paks = $smiley_paks;
		$TPL->display('admin/smilies/import');
	}
}

else if (isset($_GET['export_pack']))
{
	if ('send'==$_GET['export_pack']) {
		// Export our smiley config as a smiley pak...
		$resultset = $db->uFetchAll("SELECT * FROM {$db->TBL->bbsmilies}");
		if (!isset($resultset)) {
			cpg_error('The smiley list could not be obtained');
		}
		$smile_pak = '';
		for ($i = 0; $i < count($resultset); $i++ ) {
			$smile_pak .= $resultset[$i]['smile_url'] . $delimeter;
			$smile_pak .= $resultset[$i]['emoticon'] . $delimeter;
			$smile_pak .= $resultset[$i]['code'] . "\n";
		}
		header("Content-Type: text/x-delimtext; name=\"smiles.pak\"");
		header("Content-disposition: attachment; filename=smiles.pak");
		echo $smile_pak;
		exit;
	}
	require_once('header.php');
	OpenTable();
	echo '<div style="text-align:center;">';
	echo 'To create a smiley pack from your currently installed smileys, <a href="'.URL::admin('smilies&amp;export_pack=send').'">download</a> the smiles.pak file.<br />
Name this file appropriately making sure to keep the .pak file extension.<br />
Then create a zip file containing all of your smiley images plus this .pak configuration file';
	echo '</div>';
	CloseTable();
}

else if (isset($_GET['add']))
{
	if ('POST' === $_SERVER['REQUEST_METHOD'])
	{
		// Admin has submitted changes while adding a new smiley.

		// Get the submitted data, being careful to ensure that we only
		// accept the data we are looking for.
		$data = array(
			// Convert < and > to proper htmlentities for parsing.
			'code'      => str_replace('>', '&gt;', str_replace('<', '&lt;', trim($_POST['smile_code']))),
			'smile_url' => trim($_POST['smile_url']),
			'emoticon'  => trim($_POST['smile_emotion'])
		);

		// If no code was entered complain ...
		if (!$data['code'])      { cpg_error(sprintf(_ERROR_NOT_SET, 'Smiley code')); }
		if (!$data['smile_url']) { cpg_error(sprintf(_ERROR_NOT_SET, 'Smiley url')); }

		// Save the data to the smiley table.
		$db->TBL->bbsmilies->insert($data);
		Dragonfly::getKernel()->CACHE->delete('bbsmilies');
		cpg_error('The new smiley was successfully added', 'Smiles Utility', URL::admin('smilies'));
	}

	smile_edit(array(
		'code' => '',
		'emoticon' => '',
		'smile_url' => ''
	));
}

else if (isset($_POST['updatesmiles']))
{
	if (Security::check_post() && is_array($_POST['smilies'])) {
		foreach ($_POST['smilies'] as $i => $id) {
			$db->TBL->bbsmilies->update(array('pos'=>$i), 'smilies_id='.$id);
		}
	}
	Dragonfly::getKernel()->CACHE->delete('bbsmilies');
	cpg_error('Smilies order was successfully updated', 'Smilies Position Update', URL::admin('smilies'));
}

// Admin has selected to edit a smiley.
else if (isset($_GET['edit']))
{
	$smiley_id = intval($_GET['edit']);
	if ('POST' === $_SERVER['REQUEST_METHOD'])
	{
		// Admin has submitted changes while editing a smiley.

		// Get the submitted data, being careful to ensure that we only
		// accept the data we are looking for.
		$data = array(
			// Convert < and > to proper htmlentities for parsing.
			'code'      => str_replace('>', '&gt;', str_replace('<', '&lt;', trim($_POST['smile_code']))),
			'smile_url' => trim($_POST['smile_url']),
			'emoticon'  => trim($_POST['smile_emotion'])
		);

		// If no code was entered complain ...
		if (!$data['code'])      { cpg_error(sprintf(_ERROR_NOT_SET, 'Smiley code')); }
		if (!$data['smile_url']) { cpg_error(sprintf(_ERROR_NOT_SET, 'Smiley url')); }

		// Proceed with updating the smiley table.
		$db->TBL->bbsmilies->update($data, "smilies_id={$smiley_id}");
		Dragonfly::getKernel()->CACHE->delete('bbsmilies');
		cpg_error('The smiley information was successfully updated', 'Smiles Utility', URL::admin('smilies'));
	}
	$smile_data = $db->uFetchAssoc("SELECT * FROM {$db->TBL->bbsmilies} WHERE smilies_id={$smiley_id}");
	if (empty($smile_data)) {
		cpg_error('The information for the requested smiley could not be obtained');
	}
	smile_edit($smile_data);
}

else if (isset($_GET['delete']))
{
	// Admin has selected to delete a smiley.
	$result = $db->query("DELETE FROM {$db->TBL->bbsmilies} WHERE smilies_id = ".intval($_GET['delete']));
	if (!$result) {
		cpg_error('The smiley could not be deleted');
	} else {
		Dragonfly::getKernel()->CACHE->delete('bbsmilies');
		cpg_error('The smiley was successfully deleted', 'Smiles Utility', URL::admin('smilies'));
	}
}

else {
	// This is the main display of the page before the admin has selected any options.
	Dragonfly_Output_Js::add('themes/admin/javascript/admin_smilies.js');
	require_once(CORE_PATH.'nbbcode.php');
	$smilies = get_smilies();
	// Replace htmlentites for < and > with actual character.
	for ($i = 0; $i < count($smilies); $i++) { $smilies[$i]['code'] = htmlspecialchars_decode($smilies[$i]['code']); }
	$TPL = Dragonfly::getKernel()->OUT;
	$TPL->smilies = $smilies;
	$TPL->smilies_path = $smilies_path;
	$TPL->display('admin/smilies/index');
}
